package base.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;

import com.google.gson.Gson;

import student.andlei.com.student.R;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import base.BaseBean;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;
import ui.activity.login.LoginActivity;
import utils.Logger;
import utils.NetUtils;
import utils.SPUtils;
import widget.CustomProgressDialog;

import static android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP;

public abstract class BaseNetFragment extends BaseFragment {

    /**
     * 加载提示框
     */
    private CustomProgressDialog customProgressDialog;
    private NetUtils netUtils;
    public Map<String, String> params;
    private boolean isPrepared = false, isVisible = false;//是否加载完成，是否可见
    private View currentLayout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        customProgressDialog = new CustomProgressDialog(activity, R.style.progress_dialog_loading, "加载中...");
        netUtils = new NetUtils(context);
        netUtils.initHeader();

    }

    public void refreshHeader() {
        netUtils.initHeader();
    }

    /**
     * Get请求
     *
     * @param action     请求接口的尾址
     * @param clazz      要转换的Bean类型（需继承BaseBean）
     * @param showDialog 显示加载进度条
     */
    public <T extends BaseBean> void get(final String action, Class<T> clazz, boolean showDialog) {
        if (showDialog) {
            showLoadDialog();
        }
        if (params == null) {
            params = new HashMap<>();
        }
        netUtils.get(action, params, new MyObserver(action, clazz));
        params = null;
    }

    /**
     * Post请求
     *
     * @param action     请求接口的尾址
     * @param clazz      要转换的Bean类型（需继承BaseBean）
     * @param showDialog 显示加载进度条
     */
    public <T extends BaseBean> void post(final String action, Class<T> clazz, boolean showDialog) {
        if (showDialog) {
            showLoadDialog();
        }
        if (params == null) {
            params = new HashMap<>();
        }
        netUtils.post(action, params, new MyObserver(action, clazz));
        params = null;
    }

    /**
     * Post请求
     *
     * @param action     请求接口的尾址
     * @param clazz      要转换的Bean类型（需继承BaseBean）
     * @param showDialog 显示加载进度条
     */
    public <T extends BaseBean> void post(final String action, Map json, final Class<T> clazz, boolean showDialog) {
        if (showDialog) {
            showLoadDialog();
        }
        netUtils.post(action, json, new MyObserver(action, clazz));
    }

    public abstract void success(String action, BaseBean baseBean);

    public abstract void error(String action, Throwable e);

    private class MyObserver<T extends BaseBean> implements Observer<ResponseBody> {

        private Class<T> clazz;
        private String action;
        /**
         * 返回结果状态：0、正常Bean；1、Bitmap；2、数据流
         */
        private int resultStatus = 0;

        MyObserver(String action, Class<T> clazz) {
            this.clazz = clazz;
            this.action = action;
        }

        MyObserver(String action, Class<T> clazz, int resultStatus) {
            this.clazz = clazz;
            this.action = action;
            this.resultStatus = resultStatus;
        }

        @Override
        public void onSubscribe(@NonNull Disposable d) {

        }

        @Override
        public void onNext(@NonNull ResponseBody responseBody) {
            hideLoadDialog();
            try {
                switch (resultStatus) {
                    case 0:
                        String responseString = responseBody.string();
                        Logger.i("responseString", action + "********** responseString get  " + responseString);
                        success(action, (T) new Gson().fromJson(responseString, clazz));
                        BaseBean baseBean = new Gson().fromJson(responseString,BaseBean.class);
                        if(baseBean.code ==999){
                            showToast(baseBean.msg);
                            if(getActivity()!=null){
                                getActivity().finish();
                                SPUtils.getInstance(getActivity()).put("token","");
                                Intent intent = new Intent(getActivity(),LoginActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                            }
                        }
                        break;

                    default:
                        break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(@NonNull Throwable e) {
            Logger.i("responseString", "responseString get  " + e.toString());
            error(action, e);
        }

        @Override
        public void onComplete() {
            params = null;
        }
    }

    /**
     * 显示加载提示框
     */
    public void showLoadDialog() {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                customProgressDialog.show();
            }
        });
    }

    /**
     * 隐藏加载提示框
     */
    public void hideLoadDialog() {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (customProgressDialog != null && customProgressDialog.isShowing()) {
                    customProgressDialog.dismiss();
                }
            }
        });
    }

    /**
     * 添加Fragment
     *
     * @param containerViewId 对应布局的id
     * @param fragments       所要添加的Fragment，可以添加多个
     */
    public void addFragment(int containerViewId, Fragment... fragments) {
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        if (fragments != null) {
            for (int i = 0; i < fragments.length; i++) {
                transaction.add(containerViewId, fragments[i]);
                if (i != fragments.length - 1) {
                    transaction.hide(fragments[i]);
                }
            }
            transaction.commitAllowingStateLoss();
        }
    }

    /**
     * 显示Fragment
     *
     * @param fragment 所要显示的Fragment
     */
    public void showFragment(Fragment fragment) {
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        if (fragment != null) {
            transaction.show(fragment).commitAllowingStateLoss();
        }
    }

    /**
     * 隐藏Fragment
     *
     * @param fragments 所要隐藏的Fragment，可以添加多个
     */
    public void hideFragment(Fragment... fragments) {
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        if (fragments != null) {
            for (Fragment fragment : fragments) {
                transaction.hide(fragment);
            }
            transaction.commitAllowingStateLoss();
        }
    }

    /**
     * 替换Fragment
     *
     * @param containerViewId 对应布局的id
     * @param fragment        用于替代原有Fragment的心Fragment
     */
    public void replaceFragment(int containerViewId, Fragment fragment) {
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        if (fragment != null) {
            transaction.replace(containerViewId, fragment).commitAllowingStateLoss();
        }
    }

    /**
     * 移除Fragment
     *
     * @param fragments 所要移除的Fragment，可以添加多个
     */
    public void removeFragment(Fragment... fragments) {
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        if (fragments != null) {
            for (Fragment fragment : fragments) {
                transaction.hide(fragment);
            }
            transaction.commitAllowingStateLoss();
        }
    }

//    /**
//     * 控制是否在可见情况下操作
//     * @param isVisibleToUser
//     */
//    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {
//        super.setUserVisibleHint(isVisibleToUser);
//        super.setUserVisibleHint(isVisibleToUser);
//        System.out.println("Infor_Fragment----setUserVisibleHint");
//        if (getUserVisibleHint()) {
//            System.out.println("Infor_Fragment1----" + isVisible);
//            isVisible = true;
//            //initView(root);//两个都为true,这个方法就可以一直往下执行。（此时才加载数据）
//            getBundle();
//            findViews();
//            formatData();
//            formatViews();
//        } else {
//            System.out.println("Infor_Fragment2----" + isVisible);
//            isVisible = false;
//
//            //可以做一些销毁的操作。
//        }
//    }
}
